from pathlib import Path
import sys
bath_dir = Path(__file__).parent.parent
sys.path.append(bath_dir.as_posix())

from webapp import flask_app, db
from webapp.models import Pic


help_text = "第一个参数: str 待匹配的文件名，第二个参数: int 保留文件名最后N位，第三个参数：1/0 是否提交到数据库"

try:
    note = sys.argv[1]
except IndexError:
    raise ValueError(help_text)

try:
    length = int(sys.argv[2])
except IndexError:
    length = 3

try:
    commit_to_db = bool(sys.argv[3])
except IndexError:
    commit_to_db = False

if len(note) <=5:
    raise ValueError("文件名太短可能导致匹配范围过大")

idx = 0

if __name__ == "__main__":
    with flask_app.app_context():
        print("__start__")
        for pic in Pic.query.filter(Pic.note.startswith(note)).all():
            origin_note = pic.note
            print(origin_note, "  ",origin_note[-length:])
            pic.note = origin_note[-length:]
            idx+=1
        if commit_to_db:
            db.session.commit()
        print("__end__")
    print(f" \n{idx=}, {note=}, {length=}, {commit_to_db=}\n{help_text}")
